package io.plus.user_interface.client;

import io.plus.client.ClientAioHandler;
import io.plus.interactive.AioDecodeException;
import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.interactive.Configuration;
import io.plus.interactive.user_interface.AioHandler;
import io.plus.user_interface.common.Constants;
import io.plus.user_interface.common.packet.Command;
import io.plus.user_interface.common.protocol.Decoder;
import io.plus.user_interface.common.protocol.Encoder;
import io.plus.user_interface.common.protocol.PacketImpl;
import io.plus.user_interface.common.protocol.ProtocolConstants;

import java.nio.ByteBuffer;


public class ClientAioHandlerImpl implements AioHandler, ClientAioHandler {
    private static PacketImpl heartbeatPacket = new PacketImpl(//
            Command.heartbeat_request,//
            new byte[]{ProtocolConstants.HEARTBEAT_BYTE});//


    /**
     * 编码：把业务消息包编码为可以发送的ByteBuffer 总的消息结构：消息头 + 消息体 消息头结构： 4个字节，存储消息体的长度 消息体结构：
     * 对象的json串的byte[]
     */
    @Override
    public ByteBuffer encode(Configuration configuration, AsynchronousSocketChannelContext asynchronousSocketChannelContext, io.plus.interactive.user_interface.Packet packet) {

        PacketImpl tcpPacket = (PacketImpl) packet;
        return Encoder.encode(tcpPacket, configuration, asynchronousSocketChannelContext);
    }

    @Override
    public PacketImpl decode(AsynchronousSocketChannelContext asynchronousSocketChannelContext, ByteBuffer byteBuffer, int limit, int position, int readableLength) throws AioDecodeException {
        PacketImpl packet = Decoder.decode(byteBuffer, asynchronousSocketChannelContext);
        return packet;
    }

    @Override
    public void handler(AsynchronousSocketChannelContext asynchronousSocketChannelContext, io.plus.interactive.user_interface.Packet packet) throws Exception {
        PacketImpl packet1 = (PacketImpl) packet;
        byte[] body = packet1.getBody();
        if (body != null) {
            String str = new String(body, Constants.CHARSET);
            System.out.println("收到消息：" + str);
        }

        return;
    }


    /**
     * 此方法如果返回null，框架层面则不会发心跳；如果返回非null，框架层面会定时发本方法返回的消息包
     */
    @Override
    public io.plus.interactive.user_interface.Packet heartbeatPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        return heartbeatPacket;
    }
}
